package com.atguigu.lease.web.app.custom.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author Tsuchi
 * @description TODO
 * @date 2024/12/25 19:33
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

	// 请求拦截
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String accessToken = request.getHeader("access_token");
		// 判断accessToken是否为空
		if(accessToken == null){
			// 为空就是用户未登录
			throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);
		}else{
			Claims claims = JwtUtil.parseToken(accessToken);
			Long userId = claims.get("userId", Long.class);
			String userName = claims.get("userName", String.class);

			LoginUserContext.setLoginUser(new LoginUser(userId,userName));
		}

		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		LoginUserContext.clear();
	}
}
